<?php
require_once('Extension/Controller/Action.php');

class Admin_SearchLuceneController extends Extension_Controller_Action 
{
    public function indexAction() 
    {
        $deletedInfo = '';

        try {
            $luceneIndex = Kbs::initSearchLucene('open');
            $this->view->docsTotal = $luceneIndex->count();
            $this->view->unDeletedDocsTotal = $luceneIndex->numDocs();

            
            for ($id = 0; $id < $luceneIndex->maxDoc(); $id++) {
                if ($luceneIndex->isDeleted($id)) {
                    $deletedInfo .= "Document #$id is deleted.<br />";
                }
            }
        } catch (Exception $e) {
            // don't do anything
        }

        $this->view->deletedInfo = $deletedInfo;
    }

    public function createAction()
    {
        $this->updateAction(true);
    }

    public function updateAction($isNew = false)
    {
        if ($isNew) {
            $luceneIndex = Kbs::initSearchLucene('create');
        } else {
            $luceneIndex = Kbs::initSearchLucene('open');
        }

        $encoding = $luceneIndex->encoding;

        $functionPost = new Core_Model_Function_Post();

        if ($isNew) {
            $posts = $functionPost->findAll();
        } else {
            $posts = $functionPost->findAllNotReadyForSearch();
        }

        foreach ($posts as $post) {
            $doc = new Zend_Search_Lucene_Document();

            $doc->addField(Zend_Search_Lucene_Field::UnIndexed('post_id', $post['post_id'], $encoding));

            $doc->addField(Zend_Search_Lucene_Field::Text('post_title', $post['post_title'], $encoding));
            //$doc->addField(Zend_Search_Lucene_Field::Keyword('post_title', $post['post_title'], $encoding));

            //$doc->addField(Zend_Search_Lucene_Field::UnStored('post_content', $post['post_content'], $encoding));
            $doc->addField(Zend_Search_Lucene_Field::Text('post_content', $post['post_content'], $encoding));

            $doc->addField(Zend_Search_Lucene_Field::UnIndexed('post_date_create', $post['post_date_create'], $encoding));

            $luceneIndex->addDocument($doc);

            $functionPost->updateReadyForSearch($post['post_id']);
        }

        $this->_forward('optimize');
    }

    public function optimizeAction()
    {
        $luceneIndex = Kbs::initSearchLucene('open');
        $luceneIndex->optimize();
        $this->_redirect('/admin/search-lucene');
    }

    public function deleteAction()
    {
        $luceneIndex = Kbs::initSearchLucene('delete');
        $docs = $luceneIndex->find('*');
        foreach ($docs as $doc) {
            $luceneIndex->delete($doc->id);
        }
        $this->_redirect('/admin/search-lucene');
    }

}